# Copyright (c) 2008-2009 Mikhail Chernov 
#
# This file is part of dcExplorer.
#
# dcExplorer is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 2 of the License, or
# (at your option) any later version.
#
# dcExplorer is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with dcExplorer.  If not, see <http://www.gnu.org/licenses/>.

# Scripting extension class
package dcExplorer::core::AlienFleets;
use strict;
use utf8;
use WeakRef;
use core::AlienFleet;

# Construction methods

sub new 
{
	my $proto = shift;
	my $class = ref($proto) || $proto;
	my $self = {};
	weaken($self->{Parent} = shift);
	$self->{Fleets} = [];
	$self->{ByPlanets} = {};
	$self->{ById} = {};
	bless ($self, $class);
	return $self;
}

sub set
{
	my $self = shift;
	my $fleet = shift;
	my $coord = sprintf("%04d:%04d", $fleet->getProp("x"), $fleet->getProp("y"));
	push @{$self->{Fleets}}, $fleet;
	push @{$self->{ByPlanets}->{$coord}}, $fleet;
	$self->{ById}->{$fleet->getProp('id')} = $fleet if defined $fleet->getProp('id'); 
}

# Scripting extensions

sub getFleetByID
{
	my $self = shift;
	my $fleetId = shift;
	return $self->{ById}->{$fleetId};
}

sub getFleetsByName
{
	my $self = shift;
	my $name = shift;
	return @{$self->{Fleets}} if $name eq '%';
	$name =~ s/%/.*/g;
	$name =~ s/_/./g;
	my @res;
	for my $fleet (@{$self->{Fleets}})
	{
		push @res, $fleet if defined($fleet->getProp('name')) && $fleet->getProp('name') =~ /^$name$/;
	}
	return @res;
}

sub getFleetsByLocation
{
	my $self = shift;
	my $x = shift;
	my $y = shift;
	my $coord = sprintf("%04d:%04d", $x, $y);
	return defined($self->{ByPlanets}->{$coord}) ? @{$self->{ByPlanets}->{$coord}} : ();
}

sub getEmpire
{
	my $self = shift;
	$self->{Parent}->getEmpire();
}

1;
